# from icecream import ic
import json
import pandas as pd

from get_sql_res import gen_run_detail
from gen_info_dic import gen_info_dic


def DPAT(df_run_detail):
    config = df_run_detail[df_run_detail['rule_key']
                           == 'DPAT'].iloc[0]['config']
    config = json.loads(config)
    df_testItemConfigs = pd.DataFrame(config['param']['testItemConfigs'])
    # df_testItemConfigs.to_csv('a.csv')
    # ic(df_testItemConfigs['needAdvancedCheck'].drop_duplicates().iloc[0])

    if df_testItemConfigs['needAdvancedCheck'].drop_duplicates(
    ).iloc[0] == False:
        # ic('aaa')
        df_testItemConfigs['minEntropy'] = ''
        df_testItemConfigs['minNumOfUniqueValues'] = ''
        df_testItemConfigs['kurtosis'] = ''
        df_testItemConfigs['skewness'] = ''
    else:
        df_testItemConfigs = pd.concat(
            [df_testItemConfigs, df_testItemConfigs['advancedCheck'].apply(pd.Series)], axis=1)
        # df_testItemConfigs.to_csv('d.csv')

        df_testItemConfigs = pd.concat(
            [df_testItemConfigs, df_testItemConfigs['continuityCheck'].apply(pd.Series)], axis=1)
        df_testItemConfigs = pd.concat(
            [df_testItemConfigs, df_testItemConfigs['normalizeCheck'].apply(pd.Series)], axis=1)
    # df_testItemConfigs.to_csv('d.csv')
    col_raw = [
        'order',
        'testItem',
        'lowThreshold',
        'highThreshold',
        'center',
        'spread',
        'staticLowLimit',
        'staticHighLimit',
        'maxEmptyValueRatio',
        'needAdvancedCheck',
        'minEntropy',
        'minNumOfUniqueValues',
        'kurtosis',
        'skewness']
    for column in col_raw:
        if column not in df_testItemConfigs.columns:
            df_testItemConfigs[column] = ''
    col_obj = [
        'Order',
        'TestItems',
        'Low Threshold',
        'High Threshold',
        'Center',
        'Spread',
        'Static Low Limit',
        'Static High Limit',
        'Max Empty Value (%)',
        'Advanced Check',
        'Minimum Entropy',
        'Minimum number of unique values',
        'Max absolute value of Kurtosis',
        'Max absolute value of Skewness']
    df = pd.DataFrame()
    df[col_obj] = df_testItemConfigs[col_raw]
    return df


def SPAT(df_run_detail):
    config = df_run_detail[df_run_detail['rule_key']
                           == 'SPAT'].iloc[0]['config']
    config = json.loads(config)
    df_testItemConfigs = pd.DataFrame(config['param']['testItemConfigs'])
    # df_testItemConfigs.to_csv('c.csv')
    if df_testItemConfigs['needAdvancedCheck'].drop_duplicates(
    ).iloc[0] == False:
        df_testItemConfigs['minEntropy'] = ''
        df_testItemConfigs['minNumOfUniqueValues'] = ''
        df_testItemConfigs['kurtosis'] = ''
        df_testItemConfigs['skewness'] = ''
    else:
        df_testItemConfigs = pd.concat(
            [df_testItemConfigs, df_testItemConfigs['advancedCheck'].apply(pd.Series)], axis=1)
        # df_testItemConfigs.to_csv('d.csv')
        df_testItemConfigs = pd.concat(
            [df_testItemConfigs, df_testItemConfigs['continuityCheck'].apply(pd.Series)], axis=1)
        df_testItemConfigs = pd.concat(
            [df_testItemConfigs, df_testItemConfigs['normalizeCheck'].apply(pd.Series)], axis=1)
    # df_testItemConfigs.to_csv('d.csv')
    col_raw = [
        'order',
        'testItem',
        'center',
        'spread',
        'multiple',
        'staticLowLimit',
        'staticHighLimit',
        'dataScope',
        'lastNum',
        'maxEmptyValueRatio',
        'needAdvancedCheck',
        'minEntropy',
        'minNumOfUniqueValues',
        'kurtosis',
        'skewness']
    for column in col_raw:
        if column not in df_testItemConfigs.columns:
            df_testItemConfigs[column] = ''
    col_obj = [
        'Order',
        'TestItems',
        'Data Scope by',
        'Data Scope - Range',
        'Center',
        'Spread',
        'Multiple',
        'Static Low Limit',
        'Static High Limit',
        'Max Empty Value (%)',
        'Advanced Check',
        'Minimum Entropy',
        'Minimum number of unique values',
        'Max absolute value of Kurtosis',
        'Max absolute value of Skewness']
    df = pd.DataFrame()
    df[col_obj] = df_testItemConfigs[col_raw]
    return df

def CORRELATION_RULE(df_run_detail):
    config = df_run_detail[df_run_detail['rule_key']
                           == 'CORRELATION_RULE'].iloc[0]['config']
    config = json.loads(config)
    df_testItemConfigs = pd.DataFrame(config['param']['testItemConfigs'])
    df_normalized = pd.concat(
        [df_testItemConfigs, df_testItemConfigs['bivariate'].apply(pd.Series)], axis=1)
    # ic(df_normalized)
    # df_normalized.to_csv('c.csv')
    df = pd.DataFrame()
    col_raw = ['order', 'xTestItem', 'yTestItem',
               'direction', 'center', 'spread', 'multiplier']
    for column in col_raw:
        if column not in df_normalized.columns:
            df_normalized[column] = ''
    col_obj = ['Order', 'X Variable', 'Y Variable',
               'Direction', 'Center', 'Spread', 'Multiplier']
    df[col_obj] = df_normalized[col_raw]
    return df


if __name__ == '__main__':
    rule_run_record_id = 7416
    with open('cfgs/input.json', 'r') as file:
        input = json.load(file)
    sql_info = {}
    sql_info['mysqlInfo'] = input['mysqlInfo']
    sql_info['ckInfo'] = input['ckInfo']
    df_run_detail = gen_run_detail(rule_run_record_id, sql_info)
    wafer_ids = df_run_detail['wafer_id'].drop_duplicates()
    info_dic = gen_info_dic(df_run_detail, sql_info)

    ##

    # DPAT(df_run_detail)
    df = SPAT(df_run_detail)
    # ic(df)
    # df.to_csv('e.csv')

